﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Hosting;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using MVCms.Core.PluginProvider;
using MVCms.Core.Services;


namespace MVCms.Web
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : System.Web.HttpApplication
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            #region Map Plugin Routes

            foreach (string route in PageService.GetAllUrls())
            {
                try
                {
                    routes.MapRoute(
                        route.TrimStart('/'),
                        route.TrimStart('/'),
                        new {controller = "Page", action = "Index"},
                        new string[] {"MVCms.Web.Controllers"} //Avoid Confusion with plugins
                        );
                }
                catch
                {
                    //if exception is thrown it means that the rout is already present
                    //Fail Gracefully
                }
            }


            #endregion

            #region Rout all routes to page controller
            //Maps Default Route, all routes(except setup) defaults to the page controller.
            routes.MapRoute(
                "Default", // Route name
                "{controller}/{action}/{id}", // URL with parameters
                new { controller = "Page", action = "Index", id = UrlParameter.Optional }, // Parameter defaults
                new string[] { "MVCms.Web.Controllers" }  //Avoid Confusion with plugins
            );
            #endregion

        }

        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            HostingEnvironment.RegisterVirtualPathProvider(new AssemblyResourceProvider());
            ViewEngines.Engines.Clear();

            //Get's the view engines of all plugin modules
            foreach (var customViewEngine in CustomViewEngine.GetViewEngines()) 
                ViewEngines.Engines.Add(customViewEngine);

            RegisterRoutes(RouteTable.Routes);
        }

        void Application_BeginRequest(Object sender, EventArgs e)
        {

        }

        protected void Application_AuthenticateRequest()
        {
            try
            {
                if (HttpContext.Current.User != null)
                    Membership.GetUser(true);
            }
            catch
            {

            }
        }
    }
}